package com.ecarx.camera.worker.location;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.ecarx.camera.utils.LogUtils;
import com.ecarx.camera.utils.Utils;
import com.ecarx.camera.worker.config.ConfigManager;

import java.util.List;

/**
 * 位置信息管理类
 */
public class XCLocationManager {

    private static final String TAG = "XCLocationManager";

    /**
     * 监听位置变化时的最小时间间隔（单位：毫秒）
     */
    private static final long MIN_TIME_MS = 1000;
    /**
     * 监听位置变化的最小距离间隔（单位：米）
     */
    private static final long MIN_DISTANCE_M = 10;
    /**
     * 通过经纬度获取详细地址的最大结果数
     */
    private static final int MAX_ADDRESS_RESULT_COUNT = 1;

    private final LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(@NonNull Location location) {
            LogUtils.d(TAG, "onLocationChanged, location:" + (location == null ? " null" : " not null getLongitude=" + location.getLongitude() + ";getLatitude=" + location.getLatitude()));
            if (location != null) {
                ConfigManager.getInstance().setLocation(location);
            }
        }

        @Override
        public void onProviderEnabled(@NonNull String provider) {
            LogUtils.d(TAG, "onProviderEnabled, provider:" + provider);
        }

        @Override
        public void onProviderDisabled(@NonNull String provider) {
            LogUtils.d(TAG, "onProviderDisabled, provider:" + provider);
        }
    };

    private static class Holder {
        private static final XCLocationManager INSTANCE = new XCLocationManager();
    }

    public static XCLocationManager get() {
        return XCLocationManager.Holder.INSTANCE;
    }

    /**
     * 初始化位置信息监听
     */
    public void initLocationListener() {
        LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            LogUtils.w(TAG, "initLocationListener, but locationManager is null");
            return;
        }

        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.w(TAG, "initLocationListener, no access location permission");
            return;
        }
        LogUtils.d(TAG, "initLocationListener");
        try {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_MS, MIN_DISTANCE_M, mLocationListener);
        } catch (Exception e) {
            LogUtils.w(TAG, "requestLocationUpdates for network failed, e:" + e);
        }
        try {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_MS, MIN_DISTANCE_M, mLocationListener);
        } catch (Exception e) {
            LogUtils.w(TAG, "requestLocationUpdates for gps failed, e:" + e);
        }
    }

    /**
     * 删除位置信息监听
     */
    public void removeListener() {
        LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            LogUtils.w(TAG, "removeListener, but locationManager is null");
            return;
        }
        LogUtils.d(TAG, "removeListener");
        locationManager.removeUpdates(mLocationListener);
    }

    /**
     * 获取最近的位置信息
     * @return
     */
    public Location getLastLocation() {
        LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            LogUtils.w(TAG, "getLastLocation, but locationManager is null");
            return null;
        }
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            LogUtils.w(TAG, "getLastLocation, no access location permission");
            return null;
        }
        Location location = null;
        List<String> providers = locationManager.getProviders(true);
        LogUtils.d(TAG, "getLastLocation, providers:" + providers);
        for (String provider : providers) {
            Location l = locationManager.getLastKnownLocation(provider);
            if (l == null) {
                LogUtils.d(TAG, "getLastLocation, provider:" + provider + ", location is null");
                continue;
            }
            if (location == null || l.getAccuracy() < location.getAccuracy()) {
                // Found best last known location
                location = l;
                LogUtils.d(TAG, "getLastLocation, provider:" + provider + ", location:" + (location == null ? " null" : " not null"));
            }
        }
        return location;
    }

    /**
     * 通过经纬度获取详细地址
     * @param latitude
     * @param longitude
     * @return
     */
    public List<Address> getAddress(double latitude, double longitude) {
        List<Address> addressList = null;
        Geocoder geocoder = new Geocoder(getContext());
        try {
            addressList = geocoder.getFromLocation(latitude, longitude, MAX_ADDRESS_RESULT_COUNT);
        } catch (Exception e) {
            e.printStackTrace();
        }

        LogUtils.d(TAG, "getAddress, latitude:" + latitude + ", longitude:" + longitude + ", addressList:" + addressList);
        return addressList;
    }

    /**
     * 获取上下文Context
     * @return
     */
    private Context getContext() {
        return Utils.getApp();
    }
}
